package com.iszhouhua.blog.controller.vue;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.iszhouhua.blog.common.util.Result;
import com.iszhouhua.blog.model.Category;
import com.iszhouhua.blog.model.Picture;
import com.iszhouhua.blog.model.Video;
import com.iszhouhua.blog.service.CategoryService;
import com.iszhouhua.blog.service.PictureService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("picture")
public class PictureController {

  @Autowired
  private PictureService pictureService;

  @Autowired
  private CategoryService categoryService;

  /**
   * 分页查询
   * @param page
   * @return
   */
  @GetMapping("list")
  public Result list(Page<Picture> page,String category_id) {
    QueryWrapper<Picture> queryWrapper = new QueryWrapper<>();
    if (StringUtils.isNotBlank(category_id)){
      queryWrapper.eq("category_id",category_id);
    }
    queryWrapper.orderByDesc("update_time");
    IPage<Picture> pictureIPage = pictureService.page(page, queryWrapper);
    for (Picture picture : pictureIPage.getRecords()){
      Category category = categoryService.getById(picture.getCategoryId());
      picture.setCategory(category);
    }
    return new Result(20000,"查询成功", pictureIPage);
  }

  @GetMapping
  public Result queryById(Long id){
    if (id == null){
      return Result.fail("改图片不存在",null);
    }
    Picture picture = pictureService.getById(id);
    Category category = categoryService.getById(picture.getCategoryId());
    picture.setCategory(category);
    return new Result(20000,"查询成功", picture);
  }

  @GetMapping("byCategory")
  public Result queryPictureByCategory(String categoryId){
    if (categoryId != null ){
      Category category = categoryService.getById(categoryId);
      QueryWrapper<Picture> wrapper = new QueryWrapper<>();
      wrapper.eq("category_id",category.getId());
      wrapper.orderByDesc("update_time");
      wrapper.last("limit,0,6");
      List<Picture> pictureList = pictureService.list(wrapper);
      return new Result(20000,"查询成功", pictureList);
    }
      return new Result(50000,"查询失败", null);
  }
}
